import Taro from '@tarojs/taro';
import appConfig from './appConfig';
import {showToast, reLogin, unite} from '../utils';


// 请求拦截器
/*const interceptor = function (chain) {
    const requestParams = chain.requestParams;
    const { method = 'POST', data, url } = requestParams;
    console.log(`http ${method || 'GET'} --> ${url} data: `, data)
    return chain.proceed(requestParams)
        .then(res => {
            console.log(`http <-- ${url} result:`, res)
            return res
        })
}
Taro.addInterceptor(interceptor);，
*/
// let requestTask =[];  // 用来取消多个接口100 或 101
let count = 0;
function requestAction(params, dispatch, getState, actionCreator, needLoading=true) {
    if(needLoading) {
        Taro.showLoading({
            title: '玩命加载…'
        });
    }
   // || 'd69817dr51ta2dnb82Vaa7UeaQ6dJen8337555cb05c'
    return new Promise((resolve) => {
        console.log(getState().userToken + 'getState().userToken');
        if(params.data) {
            params.data.accessToken = params.data.accessToken || getState().userToken;
        } else {
            params.data = {
                userToken: getState().userToken
            }
        }
        Taro.request({
            url: appConfig.apiurl + params.url,
            method: params.method || 'POST',
            data: params.data,
            header: {
                'content-type': 'application/json',
                'accessToken': params.data.accessToken || getState().userToken,
            },
            success: res => {
                if (needLoading) {
                    Taro.hideLoading();
                }
                switch(res.statusCode) {
                    case 200:
                        if(res.data.code == 41008 || res.data.code == 101) {
                            showToast('登录失效，请重新登录');
                            resolve(null);
                        } else if (res.data.code == 500) {
                            reLogin().then(() => {
                                Taro.switchTab({
                                    url: `/pages/home/home`
                                })
                            });
                            resolve(res.data);
                        } else if (res.data.code == 400) {
                            unite.showToast(res.data.msg);
                            resolve(res.data);
                        } else {
                            resolve(res.data);
                        }
                        break;
                    case 404:
                        showToast('请求资源不存在');
                        logErrorAction({postUrl:appConfig.apiurl + params.url, statusCode: res.statusCode, ...params.data});
                        resolve(null);
                        break;
                    case 500:
                        showToast(res.data.message);
                        logErrorAction({postUrl:appConfig.apiurl + params.url, statusCode: res.statusCode, ...params.data});
                        resolve(null);
                        break;
                    case 403:
                        showToast('没有权限访问');
                        logErrorAction({postUrl:appConfig.apiurl + params.url, statusCode: res.statusCode, ...params.data});
                        resolve(null);
                        break;
                    default:
                        logErrorAction({postUrl:appConfig.apiurl + params.url, statusCode: res.statusCode, ...params.data});
                        resolve(null);
                }
            },
            fail: (e) => {
                console.log(e);
                Taro.hideLoading();
                showToast('网络连接超时，请稍后重试');
                resolve(null);
            }
        })
    })
}

export function logErrorAction(postData, postUrl = 'save-error-log') {
    // if(postData.postUrl === appConfig.apiurl + postUrl) return;
    // try {
    //     var deviceInfo = Taro.getSystemInfoSync(); //获取设备信息
    // } catch (e) {
    //     console.error('not support getSystemInfoSync api');
    // }
    // let time = formatTime(new Date());
    // Taro.request({
    //     url: appConfig.apiurl + postUrl,
    //     method: 'POST',
    //     data: {data: postData, deviceInfo: deviceInfo, time, envType: Taro.getEnv()},
    //     header: {
    //         'content-type': 'application/json'
    //     },
    //     success: () => {
    //         console.log('错误日志上传成功');
    //     },
    //     fail: (e) => {
    //         console.log(e);
    //     }
    // })
}
export default  requestAction;
